import Vue from 'vue'
import VueRouter from 'vue-router'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'

Vue.use(VueRouter)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
let __import
if (process.env.NODE_ENV == 'development') {
    __import = file => require('@/views/' + file + '.vue').default
} else {
    __import = file => () => import('@/views/' + file + '.vue')
}
const _import = __import


// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
    { path: '/404', component: _import('common/404'), name: '404', meta: { title: '404未找到' } },
    { path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' } }
]


// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
    path: '/',
    component: _import('main'),
    name: 'main',
    redirect: { name: 'home' },
    meta: { title: '主入口整体布局' },
    children: [
        // 通过meta对象设置路由展示方式
        // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
        // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
        // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
        { path: '/home', component: _import('common/setting'), name: 'home', meta: { title: '个人中心', isTab: true } },
        { path: 'exam/exam', component: _import('exam/exam'), meta: { keepAlive: false }, name: 'exam', meta: { title: '考试', isTab: true } },
        { path: 'exam/analysis', component: _import('exam/analysis'), meta: { keepAlive: false }, name: 'demo-echarts', meta: { title: '解析', isTab: true } },
        // { path: 'question/add', component: _import('question/add'), meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'stu', component: _import('student/index'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'paper', component: _import('paper/index'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'paper/add', component: _import('paper/add'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'setting', component: _import('common/setting'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'teacher', component: _import('teacher/index'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'exam', component: _import('exam/index'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'exam/exam', component: _import('exam/exam'), meta: { keepAlive: false }, name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'exam/analysis', component: _import('exam/analysis'), meta: { keepAlive: false }, name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'record', component: _import('exam/record'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: 'self', component: _import('common/self'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },

        // { path: '/home', component: _import('common/home'), name: 'home', meta: { title: '首页' } },
        // { path: '/theme', component: _import('common/theme'), name: 'theme', meta: { title: '主题' } },
        // { path: '/demo-echarts', component: _import('demo/echarts'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
        // { path: '/demo-ueditor', component: _import('demo/ueditor'), name: 'demo-ueditor', meta: { title: 'demo-ueditor', isTab: true } }
    ],
    // beforeEnter(to, from, next) {
    //     let token = Vue.cookie.get('token')

    //     console.log('token===>', token)
    //     if (!token || !/\S/.test(token)) {
    //         clearLoginInfo()
    //         next({ name: 'login' })
    //     }
    //     next()
    // }
}
const router = new VueRouter({
    mode: 'hash',
    scrollBehavior: () => ({ y: 0 }),
    isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
    routes: globalRoutes.concat(mainRoutes)
})


// const router = new VueRouter({
//     mode: 'hash',
//     // mode: 'history', // 需要后端配合
//     routes
// })


router.beforeEach((to, from, next) => {
    let token = sessionStorage.getItem('token')
    // let token = Vue.cookie.get('token')
    if (to.path !== '/404' && to.path !== '/login' && (!token || !/\S/.test(token))) {
        console.log('to.path', to.path)
        if (to.path !== '/home') {
            alert('请登录')
        }
        clearLoginInfo()
        next('/login')
    } else {
        next()
    }
})


router.beforeEach((to, from, next) => {
    // 添加动态(菜单)路由
    // 1. 已经添加 or 全局路由, 直接访问
    // 2. 获取菜单列表, 添加并保存本地存储
    if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
        next()
    } else {
        // fnAddDynamicMenuRoutes(data.menuList)
        // router.options.isAddDynamicMenuRoutes = true
        // sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
        // // sessionStorage.setItem('permissions', JSON.stringify(permissions || '[]'))
        // next({ ...to, replace: true })
        http({
            // url: http.adornUrl('/api/menu/nav'),
            url: '/api/menu/nav',
            // ulr: process.env.VUE_APP_API + '/api/menu/nav', 
            method: 'get',
            // params: http.adornParams()
        }).then(({ data }) => {
            console.log('%c!<-------------------- 请求的菜单列表 s -------------------->', 'color:blue')
            console.log(data)
            console.log('%c!<-------------------- 请求的菜单列表 e -------------------->', 'color:blue')
            if (data && data.code === 0) {
                fnAddDynamicMenuRoutes(data.menuList)
                router.options.isAddDynamicMenuRoutes = true
                sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
                sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
                next({ ...to, replace: true })
            } else {
                sessionStorage.setItem('menuList', '[]')
                sessionStorage.setItem('permissions', '[]')
                next()
            }
        }).catch((e) => {
            console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
            router.push({ name: 'login' })
        })
    }
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
    var temp = []
    for (var i = 0; i < globalRoutes.length; i++) {
        if (route.path === globalRoutes[i].path) {
            return 'global'
        } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
            temp = temp.concat(globalRoutes[i].children)
        }
    }
    return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}


/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
    var temp = []
    for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
            temp = temp.concat(menuList[i].children)
        } else if (menuList[i].path && /\S/.test(menuList[i].path)) {
            menuList[i].path = menuList[i].path.replace(/^\//, '')
            var route = {
                // path: menuList[i].path.replace('/', '-'),
                path: menuList[i].path,
                component: null,
                name: menuList[i].path.replace('/', '-'),
                // name: menuList[i].path,
                meta: {
                    menuId: menuList[i].id,
                    parentId: menuList[i].parentId,
                    title: menuList[i].name,
                    isDynamic: true,
                    isTab: true,
                    iframeUrl: ''
                }
            }
            // url以http[s]://开头, 通过iframe展示
            if (isURL(menuList[i].path)) {
                route['path'] = `i-${menuList[i].id}`
                route['name'] = `i-${menuList[i].id}`
                route['meta']['iframeUrl'] = menuList[i].path
            } else {
                try {
                    route['component'] = _import(`${menuList[i].path}`) || null
                } catch (e) { }
            }
            routes.push(route)
        }
    }
    if (temp.length >= 1) {
        fnAddDynamicMenuRoutes(temp, routes)
    } else {
        mainRoutes.name = 'main-dynamic'
        mainRoutes.children = routes
        router.addRoutes([
            mainRoutes,
            { path: '*', redirect: { name: '404' } }
        ])
        sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
        console.log('\n')
        console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
        console.log(mainRoutes.children)
        console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
    }
}


export default router